﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AppLimit.CloudComputing.SharpBox.StorageProvider;
using AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox;
using AppLimit.CloudComputing.SharpBox;
using System.IO;

namespace DropBoxListener
{
    public partial class ListenerForm : Form
    {
        public ListenerForm()
        {
            InitializeComponent();
        }
        
        CloudStorage dropBoxStorage;
        private string fileName = "LockMyPC_GUID1.txt";

        private void btnStart_Click(object sender, EventArgs e)
        {
            dropBoxStorage = new CloudStorage();
            var dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
            // declare an access token
            ICloudStorageAccessToken accessToken = null;
            // load a valid security token from file
            using (FileStream fs = File.Open("dropboxkey.txt", FileMode.Open, FileAccess.Read, FileShare.None))
            {
                accessToken = dropBoxStorage.DeserializeSecurityToken(fs);
            }
            // open the connection 
            var storageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);
            
            MessageBox.Show("App Started");
        }
        DateTime FileModifiedTime = DateTime.MinValue;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (dropBoxStorage != null)
            {
                var file = dropBoxStorage.GetFile(fileName, dropBoxStorage.GetRoot());
                if (file != null)
                {
                    if (file.Modified > FileModifiedTime)
                    {
                        FileModifiedTime = file.Modified;
                        var accessor = file.GetDataTransferAccessor();
                        using (MemoryStream ms = new MemoryStream())
                        {
                            accessor.Transfer(ms, nTransferDirection.nDownload);
                            ms.Seek(0, SeekOrigin.Begin);
                            using (StreamReader tr = new StreamReader(ms))
                            {
                                this.textBox1.Text = tr.ReadToEnd();
                            }
                        }
                    }
                }
                else
                {
                    this.textBox1.Text = string.Empty;
                }
            }
        }
    }
}
